package com.tastyshop.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.tastyshop.domain.Email;
import com.tastyshop.domain.Member;
import com.tastyshop.service.Base64;
import com.tastyshop.service.MailService;
import com.tastyshop.service.MemberService;

@Controller
@SessionAttributes("session")
public class LoginController {

	@Autowired
	private MemberService service;

	// 로그인
	@RequestMapping(value = "login.do", method = RequestMethod.GET)
	public String loginForm() {
		return "login";
	}

	@RequestMapping(value = "loginGo.do", method = RequestMethod.POST)
	public String loginform(@RequestParam(value = "email") String email,
			Model model) {
		model.addAttribute("email", email);
		return "login";
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "login.do", method = RequestMethod.POST)
	public String loginCheck(@ModelAttribute Member member, Model model, HttpServletRequest request, HttpSession session) {
		       
		String email = member.getEmail();
		String user_pw = member.getUser_pw();

		if ((email == null || email == "")
				|| ((user_pw == null || user_pw == ""))) {
			String errorMessage = "아이디 및 패스워드를 입력해주세요.";
			model.addAttribute("message", errorMessage);
			return "login";
		}

		Member loginCheckResult = service.checkEmail(email);

		// 패스워드 인코딩
		String encodePassword = new String(Base64.encode(user_pw.getBytes()));
				
		if(loginCheckResult == null){
			model.addAttribute("message", "입력하신 정보가 일치하지 않습니다.");
			return "login";
		}
		
		if (("admin").equals(loginCheckResult.getEmail())
				&& (("admin").equals(loginCheckResult.getUser_pw()))) {
			session.setAttribute("email", email);
			session.setAttribute("user_name", loginCheckResult.getUser_name());
			session.setAttribute("nick_name", loginCheckResult.getNick_name());
			return "admin";
		}
		String url = (String) session.getAttribute("url");
		if(url != null){
			String endUrl = url.substring(11);
			if ((loginCheckResult.getUser_pw().equals(encodePassword))) {
				session.setAttribute("email", email);
				session.setAttribute("user_name", loginCheckResult.getUser_name());
				session.setAttribute("nick_name", loginCheckResult.getNick_name());
				return "redirect:" + endUrl;
			}else{
				if ((email == null || email == "")
						|| ((user_pw == null || user_pw == ""))) {
					String errorMessage = "아이디 및 패스워드를 입력해주세요.";
					model.addAttribute("message", errorMessage);
					return "login";
				}
				
				if(loginCheckResult == null){
					model.addAttribute("message", "입력하신 정보가 일치하지 않습니다.");
					return "login";
				}
			}
		}
		if ((loginCheckResult.getUser_pw().equals(encodePassword))) {
			session.setAttribute("email", email);
			session.setAttribute("user_name", loginCheckResult.getUser_name());
			session.setAttribute("nick_name", loginCheckResult.getNick_name());
			return "redirect:main.do";
		}else{
			model.addAttribute("message", "입력하신 정보가 일치하지 않습니다.");
			return "login";
		}
		
    }

	// 로그아웃
	@RequestMapping("logOut.do")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:main.do";
	}

	// 이메일찾기
	@RequestMapping(value = "emailFind.do", method = RequestMethod.GET)
	public String emailFindForm() {
		return "email_find";
	}

	@RequestMapping(value = "emailFind.do", method = RequestMethod.POST)
	public String emailFind(@ModelAttribute Member member, Model model,
			RedirectAttributes redirectAttributes, HttpServletRequest request, HttpSession session) {
		String mobile = member.getMobile();
		String user_pw = member.getUser_pw();
		if ((mobile == null || mobile == "")
				|| ((user_pw == null || user_pw == ""))) {
			String errorMessage = "휴대번호 및 패스워드를 입력해주세요.";
			model.addAttribute("message", errorMessage);
			return "email_find";
		}

		Member emailFindResult = service.emailFind(mobile);
		if (emailFindResult == null) {
			String errorMessage = "입력하신 정보가 올바르지 않습니다.";
			model.addAttribute("message", errorMessage);
			return "email_find";
		}
		
		String encodePassword = new String(Base64.encode(user_pw.getBytes()));    
		if (emailFindResult.getMobile().equals(mobile)
				&& emailFindResult.getUser_pw().equals(encodePassword)) {
			String email = emailFindResult.getEmail();
			int totalLength = email.length();
			int indexof = email.indexOf("@");
			String sub1 = email.substring(0, indexof);
			int sub2Length = (sub1.length()) / 2;
			String sub2 = sub1.substring(0, sub2Length);
			String sub3 = email.substring(indexof, totalLength);
			String findEmail = sub2 + "*****" + sub3;
			redirectAttributes.addFlashAttribute("getEmail", findEmail);
			
			return "redirect:emailFind_result.do";
		} else {
			String errorMessage = "입력하신 정보가 올바르지 않습니다.";
			model.addAttribute("message", errorMessage);
			return "email_find";
		}
	}
	
	@RequestMapping(value = "emailFind_result.do", method = RequestMethod.GET)
	public String emailFindResult(Model model, HttpServletRequest request){
		return "emailFind_result";
	}

	// 비밀번호찾기
	@RequestMapping(value = "pwdFind.do", method = RequestMethod.GET)
	public String pwdFindForm() {
		return "pwd_find";
	}

	@Autowired
	private MailService mailService;

	@RequestMapping(value = "pwdFind.do", method = RequestMethod.POST)
	public String pwdFind(@ModelAttribute Member member, RedirectAttributes redirectAttributes, Model model)
			throws Exception {
		String email = member.getEmail();
		String mobile = member.getMobile();

		Member pwdFindResult = service.pwdFind(email);
		if ((email == null || email == "")
				|| ((mobile == null || mobile == ""))) {
			String errorMessage = "이메일 및 휴대번호를 입력해주세요.";
			model.addAttribute("message", errorMessage);
			return "pwd_find";
		}
		
		if (pwdFindResult == null) {
			String errorMessage = "입력하신 정보가 올바르지 않습니다.";
			model.addAttribute("message", errorMessage);
			return "pwd_find";
		}

		if (pwdFindResult.getMobile().equals(mobile)) {
			Random rnd = new Random();

			StringBuffer rndNum = new StringBuffer();

			for (int i = 0; i < 8; i++) {
				if (rnd.nextBoolean()) {
					rndNum.append((char) ((int) (rnd.nextInt(26)) + 97));
				} else {
					rndNum.append((rnd.nextInt(10)));
				}
			}

			String temporarilyNum = rndNum.toString();
			String encodePassword = new String(Base64.encode(temporarilyNum.getBytes()));
			Map<String, String> map_search = new HashMap<String, String>();
			map_search.put("email", email);
			map_search.put("mobile", mobile);
			map_search.put("user_pw", encodePassword);
			service.pwdUpdate(map_search);

			String findEmail = pwdFindResult.getEmail();
			String findName = pwdFindResult.getUser_name();
			String findPwd = temporarilyNum;
            System.out.println(findPwd);
			Email mail = new Email();
			String subject = "[Tasty Shop] 임시 비밀번호 발송 안내 입니다.";
			String reciver = findEmail;
			String content = findName + " " + "고객님의 비밀번호는" + " " + findPwd
					+ "로 변경되었습니다. 로그인 후 패스워드를 변경해 주세요.";

			mail.setSubject(subject);
			mail.setReciver(reciver);
			mail.setContent(content);
			mailService.SendEmail(mail);

			int maillength = email.length();
			int indexof = email.indexOf("@");
			String sub = email.substring(indexof, maillength);
			String mailname = sub.substring(1, sub.length());

			redirectAttributes.addFlashAttribute("mailname", mailname);
			return "redirect:pwdFind_result.do";
		} else {
			String errorMessage = "입력하신 정보가 올바르지 않습니다.";
			model.addAttribute("message", errorMessage);
			return "pwd_find";
		}
	}
	
	@RequestMapping(value = "pwdFind_result.do", method = RequestMethod.GET)
	public String pwdFindResult(){
		return "pwdFind_result";
	}

}
